<template>
  <!-- <a-icon type="edit" class="editable-cell-icon" @click="showModal" /> -->
  <drag-modal v-model="visible" title="公式" on-ok="handleOk" @cancel="handleCancel" width="900px">
    <div>科目：
      <a-tree-select v-model="subject" show-search style="width: 30%" :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" placeholder="选择科目" allow-clear tree-default-expand-all>
        <a-tree-select-node v-for="(item,id) in dropdown" :value="item.name" :title="item.name" :key="item.id+item.name">
        </a-tree-select-node>
      </a-tree-select>
      <span class="ohp">
        取数规则：
        <a-select :default-value="dropdown[0]" style="width: 120px" v-model="number">
          <a-select-option v-for="province in FormulaList" :key="province">
            {{ province }}
          </a-select-option>
        </a-select>
      </span>
      <span class="ohp">
        预算符：
        <a-radio-group name="radioGroup" v-model="operator">
          <a-radio :value="1">
            +
          </a-radio>
          <a-radio :value="2">
            -
          </a-radio>
        </a-radio-group>
      </span>
      <span class="ohp">
        <a-button type="primary" @click="handleAdd">
          添加
        </a-button>
      </span>
    </div>
    <br>
    <div>
      <a-table bordered :data-source="dataSource" :columns="columns" :pagination="false">
        <template slot="operation" slot-scope="text, record">
          <a-popconfirm v-if="dataSource.length" title="是否删除?" @confirm="() => onDelete(record.key)">
            <a href="javascript:;">删除</a>
          </a-popconfirm>
        </template>
      </a-table>
    </div>
    <br><br><br><br><br> <br><br>
    <template slot="footer">
      <a-button key="back" @click="handleCancel">
        关闭
      </a-button>
      <a-button key="submit" type="primary" :loading="loading" @click="handleOk">
        保存
      </a-button>
    </template>
  </drag-modal>

</template>
<script>

import { save, getFormulaList, getAccountingLedgers, saveFormula } from '@/api/finance/liablities/liablitieslist'

export default {
  props: {
    stalid: Number,
    col: {
      String,
      default: ''
    },
    doindex: {
      Number,
      default: ''
    },
    uid: {
      Number,
      default: ''
    }
  },
  data () {
    return {
      treeExpandedKeys: [], // 获取公式列表
      value: undefined,
      loading: false,
      visible: false,
      // 默认列表数据
      dataSource: [],// 公式列表显示
      count: 2,
      // 列表标题
      columns: [
        {
          title: '科目',
          dataIndex: 'subject',
          width: '30%',
          scopedSlots: { customRender: 'subject' },
        },
        {
          title: '预算符',
          dataIndex: 'tap',
        },
        {
          title: '取数规则',
          dataIndex: 'number',
        },
        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      selectedItems: [],
      // 下拉菜单科目
      dropdown: [],
      // 下拉公式列表
      FormulaList: [
        '余额', '本级借方余额', '本级贷方余额', '末级借方余额', '末级贷方余额'
      ],

      subject: '',
      number: '',
      operator: 1,
      tap: '',
      accessRule: '',
      runData: [],
      davabses: [],
      stalsname: [],
      oid: '',
      setkey: '',
      datalist: []
    };
  },
  created () {
    this.Ledgers();
    this.laList();


  },
  computed: {
    filteredOptions () {
      return OPTIONS.filter(o => !this.selectedItems.includes(o));
    },
  },
  methods: {

    // 显示弹窗列表
    showModal () {
      this.visible = true;
      this.Ledgers();
      this.laList();
    },

    // 关闭弹窗列表
    handleCancel (e) {
      this.visible = false;
    },

    handleChange (selectedItems) {
      this.selectedItems = selectedItems;
    },

    // 获取列表参数
    onCellChange (key, dataIndex, value) {
      const dataSource = [...this.dataSource];
      const target = dataSource.find(item => item.key === key);
    },

    // 列表删除
    onDelete (key) {
      const dataSource = [...this.dataSource];
      this.dataSource = dataSource.filter(item => item.key !== key);
    },

    // 获取科目列表
    Ledgers () {
      getAccountingLedgers().then((rst) => {
        for (var i = 0; i < rst.data.length; i++) {
          this.stalsname[i] = rst.data[i];
          const data = { 'name': rst.data[i].name, 'id': rst.data[i].id }
          this.dropdown.push(data);
        }
      })
    },

    // 获取公式列表
    laList () {
      getFormulaList({ 'alId': this.uid }).then((row) => {
        let cont = 1;
        this.dataSource = [];
        this.datalist = row.data;
        for (let i = 0; i < row.data.length; i++) {
          this.dataSource.push({
            key: cont,
            accountingId: row.data[i].accountingId,
            accessRule: row.data[i].accessRule,
            operator: row.data[i].operator,
            // id: row.data[i].id,
            subject: row.data[i].accountingName,
            tap: row.data[i].operator == 1 ? '+' : '-',
            number: row.data[i].accessRule == 1
              ? '余额' : row.data[i].accessRule == 2
                ? '本级借方余额' : row.data[i].accessRule == 3
                  ? '本级贷方余额' : row.data[i].accessRule == 4
                    ? '末级借方余额' : row.data[i].accessRule == 5
                      ? '末级贷方余额' : '未选择'
            ,
          })
          cont++;
          this.setkey = cont;
        }
      })

    },

    // 列表添加
    handleAdd () {
      const { count, dataSource } = this;
      this.runData = [];
      if (this.subject === '') {
        this.$message.warning('请选择科目');
        return;
      }
      if (this.number === '') {
        this.$message.warning('请选择规则');
        return;
      }
      if (this.operator == 1) {
        this.tap = "+"
      } else if (this.operator) {
        this.tap = "-"
      }
      if (this.number == '余额') {
        this.accessRule = 1;
      }
      if (this.number == '本级借方余额') {
        this.accessRule = 2;
      }
      if (this.number == '本级贷方余额') {
        this.accessRule = 3;
      }
      if (this.number == '末级借方余额') {
        this.accessRule = 4;
      }
      if (this.number == '末级贷方余额') {
        this.accessRule = 5;
      }
      for (let jk = 0; jk < this.stalsname.length; jk++) {
        if (this.stalsname[jk].name == this.subject) {
          this.oid = this.stalsname[jk].id
        }
      }
      const newData = {
        key: this.setkey++,
        subject: this.subject,
        tap: this.tap,
        accountingName: this.subject,
        number: this.number,
        accessRule: this.accessRule,
        uosname: this.subject,
      };
      this.dataSource = [...dataSource, newData];
      console.log(this.dataSource)
    },

    // 列表保存 
    handleOk () {
      let rows = '';
      let data = [];
      this.runData = [];
      this.davabses = [];

      if (this.datalist.length == 0) {
        console.log(1)


        for (let i = 0; i < this.dataSource.length; i++) { // 新增数据构造
          if (this.dataSource[i].tap == "+") {
            rows = 1;
          } else if (this.dataSource[i].tap == "-") {
            rows = 2;
          }
          this.runData.push({
            'id': this.dataSource[i].id,
            'accessRule': this.dataSource[i].accessRule,
            'accountingId': this.oid,
            'accountingName': this.dataSource[i].subject,
            'operator': rows,
            'alId': this.uid,
            'type': 1,
            'col': this.col,
            'doindex': this.doindex
          })
        }
        for (let k = 0; k < this.runData.length; k++) {
          console.log(this.runData)
          if (this.runData[k]['col'] == 'FinaltermOne') {
            data = this.runData;
          }
          if (this.runData[k]['col'] == 'FinaltermTow') {
            data = this.runData;
          }
          if (this.runData[k]['col'] == 'BeginningOne') {
            data = this.runData;
          }
          if (this.runData[k]['col'] == 'BeginningTow') {
            data = this.runData;
          }
        }
        console.log(data)
        // for (let i = 0; i < this.davabses.length; i++) {
        //   if (this.davabses[i].id === this.listArray[0].line && this.davabses[i].columns === this.listArray[0].columns) {
        //     this.allList.splice(i, 1)
        //   }
        // }
        this.davabses.push(data);


        // console.log('this is complete databases', this.davabses)
        this.$emit('childByValue', this.davabses);

        setTimeout(() => {
          this.$message.success(`保存成功`);
          this.$emit('closeModal');
          this.visible = false;
        }, 500);

      } else {
        this.runData = [];
        for (let i = 0; i < this.dataSource.length; i++) { // 新增数据构造
          if (this.dataSource[i].tap == "+") {
            rows = 1;
          } else if (this.dataSource[i].tap == "-") {
            rows = 2;
          }
          this.runData.push({
            'accessRule': this.dataSource[i].accessRule,
            'accountingId': this.oid,
            'id': this.dataSource[i].id,
            'accountingName': this.dataSource[i].subject,
            'operator': rows,
            'type': 2,
            'uid': this.stalid,
            'col': this.col,
            'doindex': this.doindex
          })
        }
        for (let k = 0; k < this.runData.length; k++) {
          if (this.runData[k]['col'] == 'FinaltermOne') {
            data = { 'value': '', 'columns': '', 'line': '', 'valueType': 2, 'id': this.uid, 'assetsLiabilitiesFormulas': this.runData };
          }
          if (this.runData[k]['col'] == 'FinaltermTow') {
            data = { 'value': '', 'columns': '', 'line': '', 'valueType': 2, 'id': this.uid, 'assetsLiabilitiesFormulas': this.runData };
          }
          if (this.runData[k]['col'] == 'BeginningOne') {
            data = { 'value': '', 'columns': '', 'line': '', 'valueType': 2, 'id': this.uid, 'assetsLiabilitiesFormulas': this.runData };
          }
          if (this.runData[k]['col'] == 'BeginningTow') {
            data = { 'value': '', 'columns': '', 'line': '', 'valueType': 2, 'id': this.uid, 'assetsLiabilitiesFormulas': this.runData };
          }
        }

        this.davabses.push(data);
        console.log('this is complete databases', this.davabses)
        saveFormula(this.davabses).then((rst) => {
          if (rst.code == 200) {
            setTimeout(() => {
              this.$message.success(`保存成功`);
              this.visible = false;
            }, 500);
          }
        })
      }


    },

  },
};
</script>
<style lang="less" scoped>
  .ohp {
    margin-left: 20px;
  }

  .editable-cell {
    position: relative;
  }

  .editable-cell-input-wrapper,
  .editable-cell-text-wrapper {
    padding-right: 24px;
  }

  .editable-cell-text-wrapper {
    padding: 5px 24px 5px 5px;
  }

  .editable-cell-icon,
  .editable-cell-icon-check {
    position: absolute;
    right: 0;
    width: 20px;
    cursor: pointer;
  }

  .editable-cell-icon {
    line-height: 18px;
    display: none;
  }

  .editable-cell-icon-check {
    line-height: 28px;
  }

  .editable-cell:hover .editable-cell-icon {
    display: inline-block;
  }

  .editable-cell-icon:hover,
  .editable-cell-icon-check:hover {
    color: #108ee9;
  }

  .editable-add-btn {
    margin-bottom: 8px;
  }
</style>